package whu.cn.whushare.util;

import com.androidplus.util.StringUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;

import whu.cn.whushare.bean.Result;
import whu.cn.whushare.common.ResultCode;

@SuppressWarnings("all")
public class GsonUtil {
    public static <T> T getResult(String jsonData, TypeToken<T> type) {
        //创建一个gson对象，该对象中不包含那些未被@expose所标记的域
        Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        return (T) gson.fromJson(jsonData, type.getType());
    }

    public static <T> Result<T> fromJson(String content, Type type) {
        Result<T> result;
        if (StringUtil.isNullOrEmpty(content)) {
            result = new Result<T>(ResultCode.EMPTY.getCode(), null);
        } else {
            try {
                Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
                result = (Result<T>) gson.fromJson(content, type);
            } catch (Exception e) {
                result = new Result<T>(ResultCode.FORMAT_ERROR.getCode(), null);
                result.setMsg("Json Parse Error");
                e.printStackTrace();
            }
        }
        return result;
    }

    public static <T> T fromJsonSimple(String content, Type type) {
        T result = null;
        if (!StringUtil.isNullOrEmpty(content)) {
            try {
                Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
                result = (T) gson.fromJson(content, type);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static <T> String toJson(T t, Type type) {
        String content = null;
        if (t != null) {
            try {
                Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
                content = gson.toJson(t, type);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return content;
    }
}
